package com.webserver.core;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import com.webserver.http.HttpRequest;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClientHandler implements Runnable {
    private Socket socket;
    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            HttpRequest request = new HttpRequest(socket);

            String path = request.getUri();
            File file = new File("./webapps" + path);

            String statusCode;
            String statusReason;
            if (file.exists() && file.isFile()) {
                statusCode = " 200";
                statusReason = " OK";
            } else {
                statusCode = " 404";
                statusReason = " Not Found";
                file = new File("./webapps/root/404.html");
            }
            /*
                HTTP/1.1 200 OK(CRLF)
                Content-Type: text/html(CRLF)
                Content-Length: 2546(CRLF)(CRLF)
                1011101010101010101......
             */
            OutputStream out = socket.getOutputStream();

            String line = "HTTP/1.1";
            byte[] data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            line = "Content-Type: text/html";
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            line = "Content-Length: " + file.length();
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            out.write(13);
            out.write(10);

            FileInputStream fis = new FileInputStream(file);
            data = new byte[1024 * 10];
            int len;
            while ((len = fis.read(data)) != -1) {
                out.write(data, 0, len);
            }
            System.out.println("响应发送完毕！");




        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
